import { getWebHQRealTime, timestampToTime, formatWeek } from '@/utils';
import { reqPortfolioList, reqDateList, reqRemind } from '@/apis/portfolio.api';
import tools from '@/lib/tools';
import { ETF_STATUS } from '@/config/portfolio';
import RemindStore from '@/utils/remindStore';

const DATE_FORMAT = 'yyyy-MM-dd';
const MODE = {
  LIST: 0,
  CARD: 1,
};
export default {
  data() {
    return {
      // 列表卡片模式，默认列表
      currentMode: MODE.LIST,
      // 当前选中日期
      selectedDate: null,
      // 最大可选日期
      maxDate: new Date(),
      // 有效日期
      validDates: [],
      // 全量数据
      dataList: [],
      // 列表展示数据
      stockList: [],
      // 卡片展示数据
      cardList: [],
      // 按日期分类全量数据
      tableMap: {},
      // 按日期分类卡片数据
      cardMap: {},
      showLoading: false,
      // 精选池、跟踪池id
      portfolioId: 0,
      // 按照什么时间排序和展示
      sortTimeType: 'push_time',
      // 是否显示日期控件
      showDatePick: false,
      // 日期弹窗
      showCalendar: false,
      // 最新的接口返回数据
      lastData: null,
      // 更新字样日期
      remindDateArr: [],
    };
  },
  computed: {
    selectedDateStr() {
      if (this.selectedDate) {
        return window.Acme.formatDate(this.selectedDate, DATE_FORMAT);
      } else {
        return '';
      }
    },
  },
  mounted() {
    this.$addEventListener('onShow', () => {
      this.dealHQData();
    });
  },
  methods: {
    // 处理组合持仓数据
    handlePortfolioDataList(list, sortTimeType) {
      try {
        if (!list?.length) {
          return;
        }
        const group = list.filter(item => !!item['open_date']);
        group.sort((a, b) => (a['open_date'] < b['open_date'] ? 1 : -1));
        this.lastData = group.map(item => ({
          stock_code: item.code,
          stock_name: item.name,
          industry: item?.indicate_info?.industry || '',
          ...item,
        }));
        this.dealHQData();
      } catch (error) {
        tools.errorReport({
          name: `mixins的handlePortfolioDataList错误 ${error.name}`,
          message: `函数的入参为${JSON.stringify({
            list,
            sortTimeType,
          })}。message:${error.message}`,
          stack: error.stack,
          category: 'js',
        });
      }
    },
    dealHQData() {
      if (!this.lastData) {
        return;
      }
      getWebHQRealTime(this.lastData, dataList => {
        this.dataList = dataList;
        // 3代表'yyyy-MM-dd'
        const DATE_TYPE = 3;
        const date = timestampToTime(dataList[0]['open_date'], DATE_TYPE);
        this.tableMap[date] = [...dataList];
        this.cardMap[date] = dataList.map(item =>
          item.trade_records.sort((prev, next) =>
            prev[this.sortTimeType] < next[this.sortTimeType] ? 1 : -1
          )
        );
        this.getValidDate();
      });
    },
    async getDateList() {
      const query = {
        portfolio_id: this.portfolioId,
      };
      try {
        const res = await reqDateList(query);
        if (res.status_code) {
          throw new Error(
            `getDateList的status_code错误。入参为${JSON.stringify(query)},响应${JSON.stringify(
              res
            )}`
          );
        }
        if (!Array.isArray(res.data)) {
          throw new Error(
            `getDateList错误。入参为${JSON.stringify(query)},响应${JSON.stringify(res)}`
          );
        }
        this.validDates = res.data.sort((prev, next) =>
          +prev.replaceAll('-', '') < +next.replaceAll('-', '') ? 1 : -1
        );
        const dateStr = this.validDates[0];
        this.selectedDate = new Date(dateStr);
      } catch (err) {
        _t.errorReport({
          name: `getDateList方法错误.${err.name}`,
          stack: err.stack,
          message: err.message,
        });
      }
    },
    async getPoolData() {
      const params = {
        portfolio_id: this.portfolioId,
        open_date: this.selectedDateStr,
        status_list: Object.keys(ETF_STATUS),
        with_records: 1,
      };
      try {
        const res = await reqPortfolioList(params);
        if (res.status_code) {
          throw new Error(
            `函数getTrackPoolData的接口reqPortfolioList返回的status_code非0。入参为：${JSON.stringify(
              params
            )}；响应值为：${JSON.stringify(res)}`
          );
        }
        this.handlePortfolioDataList(res.data, this.sortTimeType);
      } catch (error) {
        tools.errorReport({
          name: `getTrackPoolData方法错误。${error.name}`,
          message: `入参为${JSON.stringify(params)}。${error.message}`,
          stack: error.stack,
        });
      }
    },
    getValidDate() {
      try {
        // 没有选中日期取最新日
        const carObj = this.cardMap[this.selectedDateStr] || [];
        this.cardList = [...carObj];
        this.stockList = [...this.tableMap[this.selectedDateStr]];
        this.showDatePick = true;
      } catch (err) {
        _t.errorReport({
          name: `getValidDate方法错误。${err.name}`,
          message: err.message,
          stack: err.stack,
          category: 'js',
        });
      }
    },
    show() {
      this.showCalendar = true;
    },

    confirm(date) {
      this.showCalendar = false;
      this.selectedDate = date;
      this.getPoolData();
    },
    filterDate(days) {
      return days.filter(day => this.validDates.includes(window.Acme.formatDate(day, DATE_FORMAT)));
    },
    filterCalendar(date) {
      return this.validDates.includes(window.Acme.formatDate(date, DATE_FORMAT));
    },
    getRemind() {
      const params = {
        portfolio_ids: [this.portfolioId],
      };
      return reqRemind(params)
        .then(res => {
          if (res.status_code) {
            throw new Error(
              `getRemind接口错误。入参为${JSON.stringify(params)}，响应为${JSON.stringify(res)}`
            );
          }
          const remindDateArr = [];
          const remindStore = new RemindStore();
          res.data.forEach(item => {
            const date = window.Acme.formatDate(new Date(item.open_date), DATE_FORMAT);
            // 不在内存中，说明是新更新的数据
            if (!remindStore.in(date, item.item_id + '')) {
              // 因为目前只在最新的一天，只要展示就算做看过
              remindStore.push(date, item.item_id);
              remindDateArr.push(date);
            }
          });
          this.remindDateArr = [...new Set(remindDateArr)];
          // 使用宏任务，防止微任务过快的执行导致当前页面UI展示延迟，高亮未渲染完成
          setTimeout(() => {
            this.highlightDate();
          });
        })
        .catch(err => {
          tools.errorReport({
            name: `getRemind方法错误。${err.name}`,
            message: err.message,
            stack: err.stack,
            category: 'ajax',
          });
        });
    },
    // 高亮更新日期
    highlightDate() {
      const $renewalDom = $('.atom-calendar-tab__item-week:contains("更新")');
      $renewalDom.length && $renewalDom.css({ color: '#FF2436' });
      const $Doms = $('.atom-calendar-tab__item-week');
      $Doms.each(function () {
        if ($(this).text().indexOf('更新') === -1) {
          $(this).css({ color: '' });
        }
      });
    },
    formatter(day) {
      if (this.remindDateArr.includes(window.Acme.formatDate(day.date, DATE_FORMAT))) {
        day.topInfo = '更新';
        day.className = 'renewal-day';
      }
      return day;
    },
    weekFormatter(date) {
      if (this.remindDateArr.includes(window.Acme.formatDate(date, DATE_FORMAT))) {
        return '更新';
      } else {
        return formatWeek(date);
      }
    },
  },
};
